<template>
  <!-- 画布 -->
  <div ref="chartRef" style="width: 100%; height: 500px;"></div>
</template>

<script setup>
import { onMounted, onBeforeUnmount, ref } from 'vue';
import * as echarts from 'echarts';
import { orderTotaldata } from '@/api/home';

const homeInfo = ref();
const chartRef = ref(null);
let chart;

const getHomeInfo = async () => {
  try {
    let res = await orderTotaldata();
    console.log(res);
    homeInfo.value = res;

    if (homeInfo.value) {
      const option = {
        title: { text: '数据统计' },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'line',
          }
        },
        legend: {
          data: ['订单量', '销售额', '注册人数', '管理员人数']
        },
        // 调整 grid 组件，改变图左右边距
        grid: {
          left: '6%',
          right: '6%'
        },
        // 声明一个 X 轴，类目轴（category）。默认情况下，类目轴对应到 dataset 第一列。
        xAxis: [
          {
            type: 'category',
            // 减少两端空白 线到坐标轴
            boundaryGap: false,
            data: homeInfo.value.xData
          }
        ],
        yAxis: [
          {
            // 自适应数据
            type: 'value'
          }
        ],
        series: [
          {
            name: '订单量',
            type: 'line',
            data: homeInfo.value.orderData
          },
          {
            name: '销售额',
            type: 'line',
            data: homeInfo.value.amountData
          },
          {
            name: '注册人数',
            type: 'line',
            data: homeInfo.value.orderData
          },
          {
            name: '管理员人数',
            type: 'line',
            data: homeInfo.value.orderData
          },
        ]
      };

      if (onMounted) {
        chart = echarts.init(chartRef.value);
        chart.setOption(option);
      }
    }
  } catch (error) {
    console.error('获取数据失败:', error);
  }
};

onMounted(() => {
  getHomeInfo();
});

onBeforeUnmount(() => {
  if (chart) {
    chart.dispose();
  }
});

const handleResize = () => {
  console.log('宽高发生了改变');
  if (chart) {
    chart.resize();
  }
};

window.addEventListener('resize', handleResize);

// 销毁页面 取消监听window事件
onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize);
});
</script>